<template>
  <div class="upload-ct-step">
    <a-typography-title :heading="4">步骤1: CT图像上传与分割</a-typography-title>
    
    <div class="step-container">
      <div class="upload-section">
        <div class="section-title">
          <icon-upload />
          <span>上传CT图像</span>
        </div>
        
        <a-upload
          :custom-request="handleUpload"
          :file-list="fileList"
          :limit="10"
          multiple
          accept=".png,.jpg,.jpeg,.bmp,.dcm"
          @change="handleChange"
          @exceed-limit="handleExceed"
          :auto-upload="true"
          :show-file-list="true"
          list-type="text"
        >
          <template #upload-button>
            <div class="upload-area">
              <div class="upload-icon">
                <icon-file-image :style="{ fontSize: '48px', color: 'rgb(var(--primary-6))' }" />
              </div>
              <div class="upload-text">
                <p>点击或拖拽文件到此处上传</p>
                <p class="upload-hint">支持上传PNG、JPG、JPEG、BMP和DICOM格式CT图像</p>
              </div>
            </div>
          </template>
        </a-upload>
        
        <div class="upload-info">
          <a-alert type="info">
            已上传 {{ fileList.length }} 个文件
          </a-alert>
        </div>
        
        <a-divider />
        
        <div class="segmentation-options">
          <a-typography-title :heading="6">分割设置</a-typography-title>
          <a-form layout="vertical">
            <a-form-item field="threshold" label="分割阈值">
              <a-slider
                v-model="segmentationThreshold"
                :min="0.1"
                :max="0.9"
                :step="0.05"
                show-ticks
                show-input
                style="width: 100%"
              />
              <a-typography-paragraph type="secondary" style="font-size: 12px; margin-top: 4px;">
                阈值越高，分割结果越严格；越低则越宽松。建议值: 0.5
              </a-typography-paragraph>
            </a-form-item>
          </a-form>
        </div>
        
        <div class="action-buttons">
          <a-button type="primary" :disabled="fileList.length === 0" @click="startSegmentation">
            开始分割并生成描述
          </a-button>
        </div>
      </div>
      
      <div class="result-section">
        <div class="section-title">
          <icon-robot />
          <span>AI分割结果</span>
        </div>
        
        <div v-if="segmentationStatus === 'waiting'" class="empty-result">
          <a-empty description="请先上传CT图像并开始分割" />
        </div>
        
        <div v-else-if="segmentationStatus === 'processing'" class="processing-result">
          <a-spin tip="正在进行AI分割，请稍候..." />
          <a-progress 
            :percent="segmentationProgress / 100" 
            :animation="true"
            status="normal"
          >
            <template v-slot:text="scope">
              {{ Math.round(scope.percent * 100) }}%
            </template>
          </a-progress>
        </div>
        
        <div v-else-if="segmentationStatus === 'completed'" class="segmentation-result">
          <!-- 添加CTClip使用提示 -->
          <a-alert type="info" class="ctclip-tip" banner style="margin-bottom: 16px;">
            <template #icon><icon-bulb /></template>
            <template #message>
              <span>提示: 分割完成后将<b>自动</b>使用CTClip模型对<b>叠加结果图像</b>进行分析，生成文本描述。您也可以点击任意分割结果下方的<b>'生成描述'</b>按钮手动触发分析。</span>
            </template>
          </a-alert>
          
          <a-tabs :active-key="activeTabbedKey" @update:active-key="activeTabbedKey = $event">
            <a-tab-pane key="1" title="分割结果预览">
              <div class="result-preview">
                <div v-for="(result, index) in segmentationResults" :key="index" class="result-item">
                  <div class="result-title">{{ result.fileName }}</div>
                  <a-tabs type="card">
                    <a-tab-pane key="vis" title="可视化结果">
                      <div class="result-image">
                        <a-image :src="result.previewUrl" alt="可视化结果" :preview="true" />
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="overlay" title="叠加结果">
                      <div class="result-image">
                        <a-image :src="result.segmentedUrl" alt="叠加结果" :preview="true" />
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="mask" title="分割掩码">
                      <div class="result-image">
                        <a-image :src="result.maskUrl" alt="分割掩码" :preview="true" />
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="prob" title="概率图">
                      <div class="result-image">
                        <a-image :src="result.probUrl" alt="概率图" :preview="true" />
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="original" title="原始图像">
                      <div class="result-image">
                        <a-image :src="result.originalUrl" alt="原始图像" :preview="true" />
                      </div>
                    </a-tab-pane>
                  </a-tabs>
                  <div class="result-info">
                    <a-space>
                      <a-tag color="blue">已完成分割</a-tag>
                      <a-tag color="green">处理时间: {{ (index + 1) * 0.8 }}秒</a-tag>
                      <a-button 
                        type="outline" 
                        size="small" 
                        status="success" 
                        @click="selectImageForCTClip(result)"
                        :loading="isProcessingCtClip && ctClipStatus === 'processing'"
                      >
                        <template #icon><icon-bulb /></template>
                        生成描述
                      </a-button>
                    </a-space>
                  </div>
                </div>
                <div v-if="segmentationResults.length === 0" class="empty-result-message">
                  <a-empty description="暂无分割结果，请上传图像并点击分割按钮" />
                </div>
              </div>
            </a-tab-pane>
            
            <a-tab-pane key="4" title="存储图像">
              <div class="stored-images">
                <a-alert type="info" style="margin-bottom: 16px;">
                  <template #message>
                    显示后端存储的所有图像，可以直接选择这些图像进行分析
                  </template>
                </a-alert>
                
                <a-spin :loading="loadingStoredImages">
                  <a-grid :cols="{ xs: 1, sm: 2, md: 3, lg: 4, xl: 4, xxl: 6 }" :colGap="16" :rowGap="16">
                    <a-grid-item v-for="(image, index) in storedImages" :key="index">
                      <a-card class="stored-image-card" :bodyStyle="{ padding: '8px' }">
                        <template #cover>
                          <div class="stored-image-container">
                            <a-image :src="image.path" :alt="image.name" :preview="true" />
                          </div>
                        </template>
                        <a-typography-text ellipsis>{{ image.name }}</a-typography-text>
                        <div class="stored-image-actions">
                          <a-button 
                            type="primary" 
                            size="small" 
                            @click="useStoredImage(image)"
                          >
                            使用此图像
                          </a-button>
                        </div>
                      </a-card>
                    </a-grid-item>
                  </a-grid>
                  
                  <div v-if="storedImages.length === 0 && !loadingStoredImages" class="empty-result">
                    <a-empty description="暂无存储图像" />
                  </div>
                </a-spin>
                
                <div class="refresh-button" style="margin-top: 16px; text-align: center;">
                  <a-button @click="fetchStoredImages">
                    <template #icon><icon-refresh /></template>
                    刷新图像列表
                  </a-button>
                </div>
              </div>
            </a-tab-pane>
            
            <a-tab-pane key="2" title="分割统计">
              <a-descriptions :data="segmentationStats" layout="vertical" />
            </a-tab-pane>
            
            <a-tab-pane key="3">
              <template #title>
                <span style="display: flex; align-items: center; gap: 4px;">
                  <span>CTClip预测结果</span>
                  <a-badge v-if="ctClipStatus === 'completed'" status="success" />
                  <a-badge v-else-if="ctClipStatus === 'processing'" status="processing" />
                </span>
              </template>
              <div class="ctclip-results">
                <div v-if="ctClipStatus === 'waiting'" class="empty-result">
                  <a-empty description="请先点击某个分割结果中的'生成描述'按钮" />
                </div>
                
                <div v-else-if="ctClipStatus === 'processing'" class="processing-result">
                  <a-spin tip="正在使用CTClip模型生成描述，请稍候..." />
                </div>
                
                <div v-else-if="ctClipStatus === 'completed' && ctClipResult" class="completed-result">
                  <a-card title="CT图像描述" bordered>
                    <a-typography-title :heading="5">
                      顶部预测结果
                    </a-typography-title>
                    <div class="top-prediction">
                      <a-typography-paragraph style="font-size: 16px; font-weight: 500;">
                        {{ ctClipResult.top_prediction.label }}
                      </a-typography-paragraph>
                      <a-tag color="blue">
                        置信度: {{ (ctClipResult.top_prediction.probability * 100).toFixed(2) }}%
                      </a-tag>
                    </div>
                    
                    <a-divider />
                    
                    <a-typography-title :heading="5">
                      所有预测结果
                    </a-typography-title>
                    <a-table :data="ctClipResult.predictions" :bordered="false" :pagination="false">
                      <template #columns>
                        <a-table-column title="描述" data-index="label" />
                        <a-table-column title="置信度" data-index="probability">
                          <template #cell="{ record }">
                            {{ (record.probability * 100).toFixed(2) }}%
                          </template>
                        </a-table-column>
                      </template>
                    </a-table>
                    
                    <a-typography-paragraph style="margin-top: 16px;" type="secondary">
                      注: CTClip模型根据CT图像生成的文本描述将作为诊断报告的参考内容
                    </a-typography-paragraph>
                  </a-card>
                </div>
                
                <div v-else-if="ctClipStatus === 'error'" class="error-result">
                  <a-result status="error" title="CTClip处理失败" sub-title="请重新尝试">
                    <template #extra>
                      <a-button type="primary" @click="ctClipStatus = 'waiting'">重试</a-button>
                    </template>
                  </a-result>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </div>
        
        <div v-else-if="segmentationStatus === 'error'" class="error-result">
          <a-result status="error" title="分割失败" sub-title="请检查上传的图像格式是否正确">
            <template #extra>
              <a-button type="primary" @click="resetSegmentation">重新上传</a-button>
            </template>
          </a-result>
        </div>
        
        <div class="next-step-button" v-if="segmentationStatus === 'completed'">
          <a-alert type="success">
            分割完成，可以进入下一步
          </a-alert>
          <a-button type="primary" @click="goToNextStep">
            下一步: 上传病历报告
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { IconUpload, IconFileImage, IconRobot, IconBulb, IconRefresh } from '@arco-design/web-vue/es/icon';
import { segmentationApi, ctClipApi, imageApi } from '@/services/api';
import { useWorkflowStore } from '@/stores/workflow';

const emit = defineEmits(['next', 'save']);
const workflowStore = useWorkflowStore();

// 文件上传相关
const fileList = ref<any[]>([]);
const uploadedFiles = ref<any[]>([]);

// 分割状态：waiting, processing, completed, error
const segmentationStatus = ref('waiting');
const segmentationProgress = ref(0);
const segmentationResults = ref<any[]>([]);
const segmentationThreshold = ref(0.5); // 分割阈值

// CTClip状态
const ctClipStatus = ref('waiting'); // waiting, processing, completed, error
const ctClipProgress = ref(0);
const ctClipResult = ref<any>(null);
const isProcessingCtClip = ref(false);
const activeTabbedKey = ref('1'); // 当前激活的标签页

// 计算属性：确保进度百分比不超过100
const segmentationProgressPercent = computed(() => {
  return Math.min(segmentationProgress.value, 100);
});

// 计算分割结果统计数据
const segmentationStats = computed(() => {
  if (segmentationResults.value.length === 0) {
    return [];
  }
  
  // 基于实际分割结果计算统计数据
  return [
    {
      label: '已处理图像数量',
      value: `${segmentationResults.value.length} 张`
    },
    {
      label: '分割完成率',
      value: '100%'
    },
    {
      label: '平均处理时间',
      value: `${(segmentationResults.value.length * 0.8).toFixed(1)} 秒`
    }
  ];
});

// 存储的图像列表
const storedImages = ref<any[]>([]);
const loadingStoredImages = ref(false);

// 组件挂载时获取存储的图像
onMounted(() => {
  fetchStoredImages();
});

// 从后端获取已存储的图像列表
const fetchStoredImages = async () => {
  loadingStoredImages.value = true;
  try {
    // 使用imageApi获取结果
    const data = await imageApi.getResults();
    console.log('获取到已存储的图像列表:', data);
    
    // 如果后端返回的是标准格式
    if (data && data.success && Array.isArray(data.results)) {
      storedImages.value = data.results.map((result: any) => {
        return {
          name: result.name,
          path: result.url,
          type: result.type || 'stored',
          id: result.id
        };
      });
      console.log('已加载存储图像:', storedImages.value.length);
    } else {
      // 尝试使用备用方法获取
      console.warn('API返回格式不符合预期，尝试备用方法');
      const files = await imageApi.getDirectoryFiles('/static/results');
      
      if (Array.isArray(files)) {
        storedImages.value = files.map((filename: string) => {
          return {
            name: filename,
            path: imageApi.getResultImageUrl(filename),
            type: 'stored'
          };
        });
        console.log('使用备用方法加载图像:', storedImages.value.length);
      } else {
        throw new Error('无法获取图像列表');
      }
    }
  } catch (error: any) {
    console.error('获取存储图像失败:', error);
    Message.error(`获取已存储图像列表失败: ${error.message || '未知错误'}`);
    storedImages.value = []; // 确保在错误情况下也有一个空数组
  } finally {
    loadingStoredImages.value = false;
  }
};

// 使用存储的图像
const useStoredImage = async (image: any) => {
  try {
    // 从URL获取图像
    const response = await fetch(image.path);
    if (!response.ok) {
      throw new Error(`获取图像失败: ${response.status}`);
    }
    
    const blob = await response.blob();
    
    // 创建文件对象
    const file = new File([blob], image.name, { type: blob.type || 'image/png' });
    
    // 将文件添加到上传列表
    fileList.value.push({
      uid: Date.now().toString(),
      name: image.name,
      file: file,
      status: 'done'
    });
    
    Message.success(`已添加图像: ${image.name}`);
    
    // 如果是分割后的图像，可以直接使用它进行CTClip分析
    if (image.name.includes('overlay') || image.name.includes('segmented')) {
      const result = {
        fileName: image.name,
        segmentedUrl: image.path
      };
      selectImageForCTClip(result);
    }
  } catch (error: any) {
    console.error('使用存储图像失败:', error);
    Message.error(`使用图像失败: ${error.message || '未知错误'}`);
  }
};

// 处理文件上传
const handleUpload = (options: any) => {
  console.log('handleUpload被调用，选项:', options);
  console.log('options类型:', typeof options);
  console.log('options.fileItem:', options.fileItem);
  
  const { onProgress, onSuccess, onError } = options;
  
  try {
    // 从fileItem中获取文件对象
    if (!options.fileItem || !options.fileItem.file) {
      throw new Error('无效的文件对象');
    }
    
    const file = options.fileItem.file;
    console.log('文件对象:', file);
    console.log('文件名称:', file.name, '类型:', file.type, '大小:', file.size);
    
    // 模拟上传进度
    onProgress({ percent: 100 });
    
    // 标记为上传成功
    onSuccess();
    
    // 添加到上传文件列表
    uploadedFiles.value.push({
      uid: options.fileItem.uid || Date.now().toString(),
      name: file.name,
      file: file
    });
    
    Message.success(`文件 ${file.name} 已准备好`);
    
    return {
      abort: () => console.log('上传已中止')
    };
  } catch (error: any) {
    console.error('文件处理失败:', error);
    onError && onError(error);
    Message.error(`文件处理失败: ${error.message || '未知错误'}`);
    return {
      abort: () => console.log('上传已中止')
    };
  }
};

// 处理文件列表变化
const handleChange = (files: any) => {
  console.log('handleChange被调用，文件列表:', files);
  
  if (files && files.length > 0) {
    console.log('第一个文件项:', files[0]);
    console.log('文件项类型:', typeof files[0]);
    console.log('文件项属性:', Object.keys(files[0]));
    
    if (files[0].file) {
      console.log('文件对象:', files[0].file);
      console.log('文件对象类型:', typeof files[0].file);
      console.log('是否是File实例:', files[0].file instanceof File);
    }
  }
  
  fileList.value = files;
};

const handleExceed = () => {
  Message.warning('超出最大上传数量限制');
};

// 开始分割
const startSegmentation = async () => {
  if (fileList.value.length === 0) {
    Message.warning('请先上传CT图像');
    return;
  }
  
  segmentationStatus.value = 'processing';
  segmentationProgress.value = 0;
  
  try {
    // 设置初始进度
    segmentationProgress.value = 10;
    console.log('开始处理文件列表:', fileList.value);
    
    // 遍历上传的所有图像文件并进行分割
    const segmentationPromises = fileList.value.map(async (fileItem, index) => {
      // 更新进度
      segmentationProgress.value = 10 + Math.floor((index / fileList.value.length) * 40);
      
      // 从fileItem中获取文件对象
      if (!fileItem.file) {
        throw new Error(`文件 ${fileItem.name || '未知'} 不存在或无效`);
      }
      
      const file = fileItem.file;
      console.log(`处理文件 ${index + 1}/${fileList.value.length}:`, file.name);
      
      // 调用分割API
      const result = await segmentationApi.segmentImage(file, segmentationThreshold.value);
      console.log('分割结果:', result);
      
      // 确保所有URL都是完整路径
      const baseUrl = window.location.origin;
      const ensureFullUrl = (url: string) => {
        if (!url) return '';
        if (url.startsWith('http')) return url;
        return url.startsWith('/') ? `${baseUrl}${url}` : `${baseUrl}/${url}`;
      };
      
      // 构建结果对象
      const resultPaths = result.result_paths || {};
      return {
        fileName: file.name,
        originalUrl: ensureFullUrl(result.original_image || ''),
        previewUrl: ensureFullUrl(resultPaths.vis || ''),
        segmentedUrl: ensureFullUrl(resultPaths.overlay || ''),
        maskUrl: ensureFullUrl(resultPaths.mask || ''),
        probUrl: ensureFullUrl(resultPaths.prob || '')
      };
    });
    
    // 更新进度到50%
    segmentationProgress.value = 50;
    
    // 等待所有分割任务完成
    const results = await Promise.all(segmentationPromises);
    segmentationProgress.value = 90;
    segmentationResults.value = results;
    
    // 分割完成
    segmentationProgress.value = 100;
    segmentationStatus.value = 'completed';
    Message.success('图像分割完成');
    
    // 自动处理第一个结果
    if (results.length > 0) {
      setTimeout(() => {
        autoProcessFirstResultWithCTClip(results[0]);
      }, 1000);
    }
  } catch (error: any) {
    console.error('分割失败:', error);
    segmentationStatus.value = 'error';
    Message.error(`图像分割失败: ${error.message || '未知错误'}`);
  }
};

// 自动处理第一个分割结果
const autoProcessFirstResultWithCTClip = async (result: any) => {
  try {
    Message.info('正在自动处理分割结果并生成描述...');
    
    // 确保URL是完整路径
    const segmentedUrl = result.segmentedUrl;
    console.log('使用图像URL:', segmentedUrl); // 调试输出
    
    // 检查URL是否有效
    if (!segmentedUrl) {
      throw new Error('无效的图像URL');
    }
    
    // 从URL获取图像文件 - 使用叠加图
    const response = await fetch(segmentedUrl);
    if (!response.ok) {
      throw new Error(`获取图像失败: ${response.status}`);
    }
    
    const blob = await response.blob();
    
    // 修改文件名，添加overlay标识（如果还没有的话）
    const originalFileName = result.fileName;
    const fileExt = originalFileName.split('.').pop();
    const fileNameWithoutExt = originalFileName.replace(`.${fileExt}`, '');
    const newFileName = originalFileName.includes('overlay') 
      ? originalFileName 
      : `${fileNameWithoutExt}_overlay.${fileExt}`;
    
    const file = new File([blob], newFileName, { type: blob.type || 'image/png' });
    
    // 处理CTClip
    await processCTClip(file);
    
    // 提示用户处理完成
    Message.success({
      content: '已自动处理分割结果并生成CT描述',
      duration: 3000
    });
    
    // 切换到CTClip预测结果标签页
    activeTabbedKey.value = '3';
  } catch (error: any) {
    console.error('自动处理分割结果失败:', error);
    Message.error(`自动生成CT描述失败: ${error.message || '未知错误'}，请手动点击"生成描述"按钮`);
  }
};

// 重置分割
const resetSegmentation = () => {
  fileList.value = [];
  uploadedFiles.value = [];
  segmentationStatus.value = 'waiting';
  segmentationProgress.value = 0;
  segmentationResults.value = [];
};

// 进入下一步
const goToNextStep = () => {
  // 保存当前步骤数据
  const uploadData = {
    ctImages: fileList.value.map(file => ({
      name: file.name,
      type: file.file.type,
      size: file.file.size
    })),
    segmentationResults: segmentationResults.value.map(result => ({
      fileName: result.fileName,
      originalUrl: result.originalUrl,
      maskUrl: result.maskUrl,
      overlayUrl: result.segmentedUrl,
      visUrl: result.previewUrl,
      probUrl: result.probUrl
    }))
  };
  
  // 保存到Pinia状态管理
  workflowStore.saveCTUploadResults(uploadData);
  
  // 通过emit将数据传递给父组件
  emit('save', uploadData);
  
  // 进入下一步
  emit('next');
};

// 处理CTClip预测
const processCTClip = async (imageFile: File) => {
  if (!imageFile) {
    Message.warning('无效的图像文件');
    return;
  }

  try {
    isProcessingCtClip.value = true;
    ctClipStatus.value = 'processing';
    
    // 自动切换到CTClip预测结果标签页
    activeTabbedKey.value = '3';
    
    // 调用CTClip API
    const result = await ctClipApi.predictDescription(imageFile);
    
    // 保存结果
    ctClipResult.value = result;
    
    // 将结果保存到状态管理中
    workflowStore.saveCtClipPredictions(result);
    
    ctClipStatus.value = 'completed';
    Message.success({
      content: '已成功生成CT图像描述，结果显示在"CTClip预测结果"标签页',
      duration: 5000
    });
  } catch (error: any) {
    console.error('CTClip处理失败:', error);
    ctClipStatus.value = 'error';
    Message.error(`生成CT图像描述失败: ${error.message || '未知错误'}`);
  } finally {
    isProcessingCtClip.value = false;
  }
};

// 选择要进行CTClip处理的图像
const selectImageForCTClip = async (result: any) => {
  // 从URL获取图像文件 - 使用叠加结果图片(overlay)
  try {
    // 确保URL是完整路径
    const segmentedUrl = result.segmentedUrl;
    console.log('手动选择图像URL:', segmentedUrl); // 调试输出
    
    // 检查URL是否有效
    if (!segmentedUrl) {
      throw new Error('无效的图像URL');
    }
    
    const response = await fetch(segmentedUrl);
    if (!response.ok) {
      throw new Error(`获取图像失败: ${response.status}`);
    }
    
    const blob = await response.blob();
    
    // 修改文件名，添加overlay标识（如果还没有的话）
    const originalFileName = result.fileName;
    const fileExt = originalFileName.split('.').pop();
    const fileNameWithoutExt = originalFileName.replace(`.${fileExt}`, '');
    const newFileName = originalFileName.includes('overlay') 
      ? originalFileName 
      : `${fileNameWithoutExt}_overlay.${fileExt}`;
    
    const file = new File([blob], newFileName, { type: blob.type || 'image/png' });
    
    // 处理CTClip
    processCTClip(file);
    
    // 切换到CTClip预测结果标签页
    activeTabbedKey.value = '3';
  } catch (error: any) {
    console.error('获取图像文件失败:', error);
    Message.error(`获取图像文件失败: ${error.message || '未知错误'}`);
  }
};
</script>

<style scoped>
.upload-ct-step {
  padding: var(--spacing-md) 0;
}

.step-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-xl);
}

.section-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-weight: 600;
  font-size: 16px;
  margin-bottom: var(--spacing-md);
  color: var(--color-text-1);
}

.upload-section, .result-section {
  background-color: var(--color-bg-2);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xl);
  border: 2px dashed var(--color-border-3);
  border-radius: var(--radius-md);
  background-color: var(--color-fill-1);
  transition: all 0.3s;
  cursor: pointer;
  min-height: 200px;
}

.upload-area:hover {
  border-color: rgb(var(--primary-6));
  background-color: rgba(var(--primary-1), 0.3);
}

.upload-icon {
  margin-bottom: var(--spacing-lg);
}

.upload-text {
  text-align: center;
}

.upload-hint {
  color: var(--color-text-3);
  font-size: 12px;
  margin-top: var(--spacing-sm);
}

.upload-info {
  margin-top: var(--spacing-lg);
}

.action-buttons {
  margin-top: var(--spacing-md);
  display: flex;
  justify-content: center;
}

.empty-result, .processing-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  gap: var(--spacing-lg);
}

.segmentation-result {
  flex: 1;
  min-height: 300px;
}

.result-preview {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
  margin-top: var(--spacing-md);
}

.result-item {
  border: 1px solid var(--color-border-2);
  border-radius: var(--radius-md);
  overflow: hidden;
  transition: all 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background-color: var(--color-bg-1);
}

.result-title {
  font-weight: 500;
  padding: var(--spacing-sm) var(--spacing-md);
  border-bottom: 1px solid var(--color-border-2);
  background-color: var(--color-fill-1);
}

.result-image {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-fill-1);
  padding: var(--spacing-md);
}

.result-image :deep(img) {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.result-info {
  padding: var(--spacing-sm) var(--spacing-md);
  font-size: 14px;
  background-color: var(--color-bg-1);
}

.empty-result-message {
  margin-top: var(--spacing-lg);
  text-align: center;
}

.next-step-button {
  margin-top: var(--spacing-lg);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.custom-progress {
  width: 100%;
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin-top: 8px;
  overflow: hidden;
}

.custom-progress-bar {
  height: 100%;
  background-color: #2080f0;
  border-radius: 4px;
  transition: width 0.2s ease;
}

:deep(.arco-tabs-type-card .arco-tabs-content) {
  padding: 0;
}

:deep(.arco-image) {
  width: 100%;
  height: 100%;
}

:deep(.arco-image-img) {
  object-fit: contain;
}

.ctclip-results {
  min-height: 300px;
}

.top-prediction {
  background-color: var(--color-fill-1);
  padding: var(--spacing-md);
  border-radius: var(--radius-md);
  margin-bottom: var(--spacing-md);
}

.stored-images {
  margin-top: var(--spacing-md);
}

.stored-image-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-md);
  border-radius: var(--radius-md);
  overflow: hidden;
  transition: all 0.2s;
}

.stored-image-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-radius: var(--radius-md);
  margin-bottom: var(--spacing-md);
}

.stored-image-actions {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-md);
}

.refresh-button {
  margin-top: var(--spacing-md);
  text-align: center;
}
</style> 